<?php

namespace Mlym\CodeGeneration\InitGeneration\Model\Method;

use EasySwoole\ORM\DbManager;
use Mlym\CodeGeneration\ClassGeneration\MethodAbstract;

class Transaction extends MethodAbstract
{

    function addMethodBody()
    {
        $this->method->setStatic();
        $this->method->addParameter('callable')->setType('callable');
        $this->method->setBody(<<<BODY
try {
    DbManager::getInstance()->startTransaction();
    \$result = \$callable();
    DbManager::getInstance()->commit();
    return \$result;
} catch (\Throwable \$throwable) {
    DbManager::getInstance()->rollback();
    throw \$throwable;
}
BODY
        );
    }

    function getMethodName(): string
    {
        return 'transaction';
    }


    public function addComment()
    {
        $comment = <<<COMMENT
Transaction
@param callable \$callable
@return mixed
@throws \Throwable
COMMENT;
        $this->method->addComment($comment);
    }
}